import React, {createContext, ReactNode, useContext, useState} from 'react';

type Props = {
  children: ReactNode;
};

type State = {
  isBindAliPay: boolean;
};

type Value = {
  set: <K extends keyof State>(key: K, value: State[K]) => void;
  state: State;
};

const UserContext = createContext<Value | undefined>(undefined);

const initialiState: State = {
  isBindAliPay: false,
};

const UserProvider = function ({children}: Props): JSX.Element {
  const [state, setState] = useState(initialiState);

  const set = function <K extends keyof State>(key: K, value: State[K]) {
    const newState: State = {...state};
    newState[key] = value;
    const params = Object.assign(state, newState);
    setState(params);
  };

  return (
    <UserContext.Provider value={{state, set}}>{children}</UserContext.Provider>
  );
};

export const useUserContext = function () {
  const ctx = useContext(UserContext);
  return ctx;
};

export default UserProvider;
